interface ObserverOption {
  storage?: 'local' | 'session'
}
export class Observer {
  cacheData: { [key: string]: any } = {}
  cacheDataOpt: { [key: string]: ObserverOption | undefined } = {}

  constructor() {}

  setCache(key: string, data: any, option?: ObserverOption) {
    this.cacheData[key] = data
    this.cacheDataOpt[key] = option

    if (option && option.storage && window) {
      window[`${option.storage}Storage`].setItem(
        key,
        ['object', 'array'].includes(typeof data) ? JSON.stringify(data) : data
      )
    }
  }

  getCache(key: string) {
    let val = this.cacheData[key]
    if (!val && this.cacheDataOpt[key] && this.cacheDataOpt[key]!.storage && window) {
      val = (window[`${this.cacheDataOpt[key]!.storage}Storage` as any] as any).getItem(key)
      try {
        val && (val = JSON.parse(val))
      } catch (er) {}
    }
    return val
  }
}
